package com.solocredit.finance.utils.dialog

import android.Manifest
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.solocredit.finance.R
import com.solocredit.finance.base.adapter.MullaRecyclerViewAdapter
import com.solocredit.finance.base.adapter.MullaViewHolderHelper
import com.solocredit.finance.base.utils.DensityUtils
import com.solocredit.finance.base.utils.dialog.BaseDialog
import com.solocredit.finance.base.utils.permission.OnPermissionCallback
import com.solocredit.finance.base.utils.permission.Permission
import com.solocredit.finance.base.utils.permission.XXPermissions
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.databinding.DialogMullaPermissionListBinding
import com.solocredit.finance.databinding.ItemMullaPermissionListChildBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.utils.decoration.LinearSpacingItemDecoration
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONArray
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/25 13:41
 * @Annotation：权限列表
 */
class PermissionListDialog: BaseDialog {
    lateinit var binding: DialogMullaPermissionListBinding
    private var mCallback: IDialogCallback? = null

    //权限描述列表
    private var permissionAdapter: PermissionItemAdapter? = null

    override fun initWindow() {
        val params = window?.attributes
        params?.width = WindowManager.LayoutParams.MATCH_PARENT
//        params?.height = MyApp.app.getPhoneHeight()
        window?.attributes = params
        window?.setWindowAnimations(R.style.picker_view_slide_anim) //修改动画样式
        window?.setGravity(Gravity.BOTTOM)
    }

    constructor(context: Context?) : super(context,R.style.LoadingDialog) {}
    constructor(context: Context?, callback: IDialogCallback?) : super(context,R.style.LoadingDialog) {
        mCallback = callback
    }

    override fun getRootView(): View {
        binding = DialogMullaPermissionListBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        initMullaRecyclerView()
        binding.ivPerLanguage.visibility = View.GONE
        if (MullaConfigs.isTanz()){
            binding.ivPerLanguage.visibility = View.VISIBLE
        }
    }

    override fun initListener() {
        setOnClickListener(binding.imgPerBack)
        setOnClickListener(binding.imgPerKefu)
        setOnClickListener(binding.ivPerLanguage)
        setOnClickListener(binding.btnDeny)
        setOnClickListener(binding.btnAgree)
        binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
            when (isChecked) {
                true -> {
                    binding.btnAgree.isEnabled = true
                }
                false -> {
                    binding.btnAgree.isEnabled = false
                }
            }
        }
    }

    override fun initData() {
        val permissionList = arrayListOf<JSONObject>()
        permissionList.add(takeMullaPerMSAGItem())
        permissionList.add(takeMullaPerDeviceItem())
        //坦桑需要显示applist权限声明
        if (MullaConfigs.isTanz()){
            permissionList.add(takeMullaPerAplItem())
        }
        permissionList.add(takeMullaPerCameraItem())
        permissionList.add(takeMullaPerStorageItem())
        permissionList.add(takeMullaPerPhoneBookItem())
        permissionList.add(takeMullaPerAlbumItem())
        permissionAdapter?.let {
            it.data = permissionList
        }
    }

    override fun onViewClick(v: View?) {
        when(v?.id){
            R.id.imgPerBack -> {//返回
                dismiss()
            }
            R.id.imgPerKefu -> {
                mCallback?.onMullaKefuClick()
            }
            R.id.ivPerLanguage -> {
                mCallback?.onMullaLanguageClick()
            }
            R.id.btnDeny -> {//拒绝
                SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_PERMISSION_LIST_STATUS,-1)
                HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_DENY,"Permission Page")
                dismiss()
                mCallback?.onMullaDenyClick()
            }
            R.id.btnAgree -> {//同意权限
                SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_PERMISSION_LIST_STATUS,1)
                HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_AGREE,"Permission Page")
                requestMullaFlowPermission()
            }
        }
    }

    /* 初始化列表 */
    private fun initMullaRecyclerView(){
//        binding.rvPermission.visibility = View.GONE
//        binding.rvPermission.setHasFixedSize(true)
//        binding.rvPermission.isNestedScrollingEnabled = false
//        binding.rvPermission.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        binding.recyclerView.layoutManager = layoutManager
        val topDecoration = DensityUtils.dp2px(14f)
        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0, 0, 0, topDecoration))
        permissionAdapter = PermissionItemAdapter(binding.recyclerView)
        permissionAdapter?.setOnItemChildClickListener { _, _, position ->
            val item = permissionAdapter?.getItem(position)
        }
        binding.recyclerView.adapter = permissionAdapter
    }

    /**
     * 授权
     */
    private fun requestMullaFlowPermission(){
        XXPermissions.with(context)
            // 申请多个权限
            .permission(Permission.READ_SMS)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                        mCallback?.onMullaAgreeClick()
                        dismiss()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))
                    //是否是广告渠道
                    val isAdSource = SharedHelper.getMullaSPBoolean(SharedHelper.MULLA_SPKEY.MULLA_IS_ADSOURCE)
                    //广告渠道跳转到权限设置页面
                    if (isAdSource){
                        XXPermissions.startPermissionActivity(context,Permission.READ_SMS)
                    }
                    mCallback?.onMullaDenyClick()
                    dismiss()
                }
            })
    }

    class PermissionItemAdapter(recyclerView: RecyclerView?) : MullaRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.item_mulla_permission_list) {

        override fun setItemChildListener(helper: MullaViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.itemLayout) //点击Item
        }

        override fun fillData(helper: MullaViewHolderHelper, position: Int, model: JSONObject) {
            val itemIcon = helper.getImageView(R.id.itemIcon)
            itemIcon.setImageResource(model.optInt("icon"))
            helper.setText(R.id.textTitle,model.optString("title"))

            val childItemLayout = helper.getView<LinearLayout>(R.id.childItemLayout)
            childItemLayout.removeAllViews()
            val itemList = model.optJSONArray("msgList")
            itemList?.let {
                for (i in 0..< itemList.length()){
                    val item = itemList.optJSONObject(i)
                    val itemView = ItemMullaPermissionListChildBinding.inflate(LayoutInflater.from(mContext))
                    val showTitle = item.optString("title")
                    if (showTitle.isNotEmpty()){
                        itemView.textTitle.text = showTitle
                        itemView.textTitle.visibility = View.VISIBLE
                    } else {
                        itemView.textTitle.visibility = View.GONE
                    }
                    itemView.textDes.text = item.optString("des")
                    childItemLayout.addView(itemView.root)
                }
            }
        }
    }

    interface IDialogCallback {
        //按钮点击
        fun onMullaKefuClick()
        fun onMullaLanguageClick()
        fun onMullaDenyClick()
        fun onMullaAgreeClick()
    }

    /**
     * sms
     */
    fun takeMullaPerMSAGItem(): JSONObject{
        val item = JSONObject()
        item.put("isSystem",true)
        item.put("icon", R.mipmap.mulla_permission_item_sms_icon)
        item.put("permission", Manifest.permission.READ_SMS)
        item.put("title", context.getString(R.string.permission_msg_title))
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", context.getString(R.string.permission_msg_why))
        obj1.put("des", context.getString(R.string.permission_msg_why_desc))
        msgArray.put(obj1)

        val obj2 = JSONObject()
        obj2.put("title", context.getString(R.string.permission_msg_do))
        obj2.put("des", context.getString(R.string.permission_msg_do_desc))
        msgArray.put(obj2)

        val obj3 = JSONObject()
        obj3.put("title", context.getString(R.string.permission_msg_data_safety))
        obj3.put("des", context.getString(R.string.permission_msg_data_safety_desc))
        msgArray.put(obj3)
        item.put("msgList",msgArray)
        return item
    }

    /**
     * device
     */
    fun takeMullaPerDeviceItem(): JSONObject{
        val item = JSONObject()
        item.put("isSystem",false)
        item.put("icon", R.mipmap.mulla_permission_item_device_icon)
        item.put("permission", context.getString(R.string.permission_device_title))
        item.put("title", context.getString(R.string.permission_device_title))
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", "")
        obj1.put("des", context.getString(R.string.permission_device_desc))
        msgArray.put(obj1)

        item.put("msgList",msgArray)
        return item
    }

    /**
     * app list
     */
    fun takeMullaPerAplItem(): JSONObject{
        val item = JSONObject()
        item.put("isSystem",false)
        item.put("icon", R.mipmap.mulla_permission_item_apl_icon)
        item.put("permission", context.getString(R.string.permission_apl_title))
        item.put("title", context.getString(R.string.permission_apl_title))
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", context.getString(R.string.permission_apl_why))
        obj1.put("des", context.getString(R.string.permission_apl_why_desc))
        msgArray.put(obj1)

        val obj2 = JSONObject()
        obj2.put("title", context.getString(R.string.permission_apl_do))
        obj2.put("des", context.getString(R.string.permission_apl_do_desc))
        msgArray.put(obj2)

        val obj3 = JSONObject()
        obj3.put("title", context.getString(R.string.permission_apl_what))
        obj3.put("des", context.getString(R.string.permission_apl_what_desc))
        msgArray.put(obj3)

        val obj4 = JSONObject()
        obj4.put("title", context.getString(R.string.permission_apl_data_safety))
        obj4.put("des", context.getString(R.string.permission_apl_data_safety_desc))
        msgArray.put(obj4)
        item.put("msgList",msgArray)
        return item
    }

    /**
     * camera
     */
    fun takeMullaPerCameraItem(): JSONObject{
        val item = JSONObject()
        item.put("isSystem",true)
        item.put("icon", R.mipmap.mulla_permission_item_camera_icon)
        item.put("permission",  Manifest.permission.CAMERA)
        item.put("title", context.getString(R.string.permission_camera_title))
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", "")
        obj1.put("des", context.getString(R.string.permission_camera_desc1))
        msgArray.put(obj1)

        val obj2 = JSONObject()
        obj2.put("title", "")
        obj2.put("des", context.getString(R.string.permission_camera_desc2))
        msgArray.put(obj2)

        val obj3 = JSONObject()
        obj3.put("title", "")
        obj3.put("des", context.getString(R.string.permission_camera_desc3))
        msgArray.put(obj3)

        item.put("msgList",msgArray)
        return item
    }

    /**
     * storage
     */
    fun takeMullaPerStorageItem(): JSONObject{
        val item = JSONObject()
        item.put("isSystem",false)
        item.put("icon", R.mipmap.mulla_permission_item_storage_icon)
        item.put("permission", context.getString(R.string.permission_storage_title))
        item.put("title", context.getString(R.string.permission_storage_title))
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", "")
        obj1.put("des", context.getString(R.string.permission_storage_desc))
        msgArray.put(obj1)

        item.put("msgList",msgArray)
        return item
    }

    /**
     * contact
     */
    fun takeMullaPerPhoneBookItem(): JSONObject{
        val item = JSONObject()
        item.put("isSystem",false)
        item.put("icon", R.mipmap.mulla_permission_item_contact_icon)
        item.put("permission", context.getString(R.string.permission_contact_title))
        item.put("title", context.getString(R.string.permission_contact_title))
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", "")
        obj1.put("des", context.getString(R.string.permission_contact_desc))
        msgArray.put(obj1)

        item.put("msgList",msgArray)
        return item
    }


    /**
     * album
     */
    fun takeMullaPerAlbumItem(): JSONObject{
        val item = JSONObject()
        item.put("isSystem",false)
        item.put("icon", R.mipmap.mulla_permission_item_album_icon)
        item.put("permission", context.getString(R.string.permission_album_title))
        item.put("title", context.getString(R.string.permission_album_title))
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", "")
        obj1.put("des", context.getString(R.string.permission_album_desc))
        msgArray.put(obj1)

        item.put("msgList",msgArray)
        return item
    }


    override fun onStart() {
        super.onStart()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_PERMISSION_START,"")
    }

    override fun dismiss() {
        super.dismiss()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_PERMISSION_END,"")
    }
}